<template>
    <div class="content">
        <div v-if="realTimeData" class="item_sight" v-for="item in tags" @click="drawRecentData(item, sensorInfo.id)" :key="item.id">
            <span>{{ item.name }}</span>
            <span>{{ realTimeData[item.nickname] }} {{ item.unit }}</span>
        </div>
        <recent-eig ref="recentEig" :sensorInfo="sensorInfo"></recent-eig>
        <div class="noData" v-if="!realTimeData">
            <span>暂无实时数据</span>
        </div>
    </div>
</template>

<script>
import { mapState } from 'vuex'
import { eigenvalueTagsApi, requestApi } from '@/requset/api'
import recentEig from '@/components/recentEig'
import { deepClone } from '@/plugins/clone'

export default {
    data() {
        return {
            topic: '',
            clients: [],
            realTimeData: null,
            tags: null,
            timer: null,
            refreshtime: 6000,
            GCdata: null,
        }
    },
    computed: {
        ...mapState('backstage', ['mqttConfig', 'sys_eig']),
    },
    props: {
        sensorInfo: {
            type: Object,
            default() {
                return null
            },
        },
    },
    components: {
        recentEig,
    },
    watch: {
        sensorInfo: {
            handler(newVal) {
                if (newVal.sys_eig) {
                    let { group_name } = newVal
                    if (this.timer) clearInterval(this.timer)
                    this.realTimeData = null
                    let { topic, address, port, single } = newVal
                    let list = newVal.sys_eig.split(',').map((item) => Number(item))
                    this.tags = []

                    // 遍历 sys_eig 数组并生成 tags
                    this.sys_eig.forEach((item) => {
                        if (list.includes(item.id)) {
                            if (item.vibration === 3) {
                                let ll = this.sensorInfo.address.includes('_') ? ['Z'] : ['X', 'Y', 'Z']
                                ll.forEach((d) => {
                                    this.tags.push({
                                        name: this.sensorInfo.address.includes('_') ? item.name : d + '轴' + item.name,
                                        nickname: item.nickname + '_' + d,
                                        unit: item.unit,
                                        id: item.id,
                                    })
                                })
                            } else {
                                this.tags.push(item)
                            }
                        }
                    })
                    if (this.sys_eig[0].sort) {
                        this.tags.sort((a, b) => this.sys_eig.find((item) => item.id === a.id).sort - this.sys_eig.find((item) => item.id === b.id).sort)
                    }
                    this.getSqlData()
                    this.timer = setInterval(() => {
                        this.getSqlData()
                    }, this.refreshtime)
                }
            },
            immediate: true,
        },
    },
    methods: {
        getSqlData() {
            requestApi('post', 'eigenvalue/sql/data', { id: this.sensorInfo.id }, false).then((res) => {
                if (res.data.data.length === 0) {
                    this.realTimeData = null
                } else {
                    this.realTimeData = {}
                    let data = res.data.data[0].data
                    for (let key in data) {
                        if (['X', 'Y', 'Z'].includes(key)) {
                            for (let k in data[key]) {
                                this.realTimeData[k + '_' + key] = data[key][k]
                            }
                        } else {
                            this.realTimeData[key] = data[key]
                        }
                    }
                    console.log('this.realTimeData', this.realTimeData)
                }
            })
        },
        getTags(id) {
            if (!id) return
            return eigenvalueTagsApi(id).then((res) => {
                if (res.data.code == 0) {
                    let list = res.data.data
                    this.tags = list
                } else this.tags = []
            })
        },
        setGCdata(e) {
            this.GCdata = e
            this.realTimeData.vel_rms_z = e.vel
            this.realTimeData.acc_rms_z = e.acc
            this.realTimeData.tem = e.tem
        },
        changeStatus(a) {
            this.$emit('changeStatus', a)
            if (this.sensorInfo.status !== a) requestApi('post', 'sensor/edit', { id: this.sensorInfo.id, status: a })
        },
        getMqttData(topic, address, port) {
            // if (this.sensorInfo.group_name == '古城') {
            //     this.realTimeData = Object.assign(deepClone(this.realTimeData), {
            //         // vel_rms_z: 2,
            //         // acc_rms_z: 1.5,
            //         // tem: 36,
            //         vel_rms_x: parseFloat((Math.random() + 1).toFixed(1)),
            //         vel_rms_y: parseFloat((Math.random() + 1).toFixed(1)),
            //         acc_rms_x: parseFloat((Math.random() + 1).toFixed(1)),
            //         acc_rms_y: parseFloat((Math.random() + 1).toFixed(1)),
            //         dis_pp_x: parseFloat((Math.random() + 5).toFixed(1)),
            //         dis_pp_y: parseFloat((Math.random() + 5).toFixed(1)),
            //         dis_pp_z: parseFloat((Math.random() + 5).toFixed(1)),
            //         audio: 35,
            //     })
            //     return
            // }
            // topic = topic + `${port}/${address}`
            // requestApi('post', 'eigenvalue/real/data', { topic }, false).then((res) => {
            //     if (res.data.code == 0) {
            //         if (res.data.data) {
            //             this.realTimeData = JSON.parse(res.data.data)
            //             let { time } = this.realTimeData
            //             if (this.isWithinTwoHours(time)) {
            //                 this.changeStatus('在线')
            //             } else {
            //                 this.changeStatus('离线')
            //             }
            //         }
            //     } else {
            //         console.log('redis出错', res.data.msg)
            //     }
            // })
        },
        isWithinTwoHours(a) {
            // 解析输入的日期字符串为 Date 对象
            const inputDate = new Date(a)
            // 获取当前时间
            const now = new Date()
            // 计算两者的差值（以毫秒为单位）
            const differenceInMilliseconds = Math.abs(inputDate - now)
            // 两小时的毫秒数
            const twoHoursInMilliseconds = 2 * 60 * 60 * 1000
            // 检查差值是否等于两小时
            return differenceInMilliseconds <= twoHoursInMilliseconds
        },
        generateGUID() {
            function s4() {
                return Math.floor((1 + Math.random()) * 0x10000)
                    .toString(16)
                    .substring(1)
            }
            return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4()
        },
        // 断开mqtt连接
        //绘制特征值最近波形图
        drawRecentData(eigkey) {
            const directionMap = {
                A: 'X',
                V: 'Y',
                H: 'Z',
            }
            this.$refs.recentEig.showRecent(this.sensorInfo.proj_no, this.sensorInfo.address.includes('_') ? this.sensorInfo.address : this.sensorInfo.address + '_0', this.sensorInfo.port, eigkey.nickname)
        },
    },
    beforeDestroy() {
        clearInterval(this.timer)
    },
}
</script>

<style lang="less" scoped>
.content {
    width: 100%;
    .title {
        height: 38px;
        line-height: 38px;
        text-indent: 10px;
        color: white;
        background-color: #0f75f0;
        border-radius: 10px;
    }
    .item_title {
        color: #007bff;
        font-size: 18px;
        font-weight: 600;
        width: 100%;
        float: left;
        margin-bottom: 10px;
    }

    .item_sight {
        width: 30%;
        float: left;
        margin-left: 2%;
        margin-bottom: 6px;
        background-color: rgba(96, 142, 235, 0.1);
        background-image: url(@/assets/common/form_item_bg.png);
        background-size: 100% 100%;
        height: 90px;
        position: relative;
        transition: all 0.3s;
        cursor: pointer;
        line-height: 16px;

        span:nth-child(1) {
            color: #b2e3ff;
            font-weight: 800;
            text-align: center;
            width: 100%;
            position: absolute;
            top: 25%;
            font-size: 14px;
        }

        span:nth-child(2) {
            color: #00ffff;
            font-weight: 500;
            text-align: center;
            width: 100%;
            position: absolute;
            top: 62%;
        }
    }

    .item_sight:hover {
        transform: scale(1.1);
        box-shadow: 0 0 1rem rgba(102, 244, 229, 0.5);
    }
    .noData {
        width: 80%;
        height: 40px;
        line-height: 40px;
        text-align: center;
        margin-left: 10%;
        // background-color: #00ffff;
        color: aliceblue;
    }
}
</style>
